from common.database import runSql
from flask import Blueprint, request
from model.User import User, db as userDb
from model.Plants import Plants, db as plantDb
from utils.JsonUtil import to_json_all  # 转json
from utils.Result import Response  # 统一返回工具类
import datetime
from sqlalchemy import desc
import json

# 蓝图名
user_blueprint = Blueprint('user', __name__)
# 创建工具类实例
Result = Response()


# 查询所有用户
# 方法
@user_blueprint.route('/getUserList', methods=['GET'])
def getAllUser():
    # 查询所有用户数据
    users = User.query.all()
    for user in users:
        # 日期格式化
        user.create_time = user.create_time.strftime('%Y-%m-%d %H:%M:%S')
    #  如何数据为空
    if not users:
        return Result.error()
    # json转换
    jsonData = to_json_all(users)
    # 成功返回
    return Result.success(jsonData)


# 登录 输入用户名和密码
@user_blueprint.route('/login', methods=['POST'])
def login():
    # 获取 POST 请求的 JSON 数据
    data = request.get_json()
    # 获取具体字段
    username = data['username']
    password = data['password']
    # 通过用户名和密码查询用户
    user = User.query.filter_by(username=username, password=password).first()  # 查询用户名是否存在
    # 如果查询为空
    if not user:
        return Result.error()
    # 进行json转换
    jsonData = to_json_all(user)
    return Result.success(jsonData)  # 登录成功，返回用户信息


# 注册
@user_blueprint.route('/register', methods=['POST'])
def register():
    # 获取 POST 请求的 JSON 数据
    data = request.get_json()
    # 获取具体字段
    username = data['username']
    password = data['password']
    nick_name = data['nick_name']
    # 这个是默认的头像地址
    imgUrl = "https://taritari-1306000991.cos.ap-chengdu.myqcloud.com/botany/1.jpg"
    # 注册添加数据
    user_data = User(nick_name=nick_name
                     , password=password
                     , username=username
                     , auth="0"
                     , create_time=datetime.datetime.now()
                     , title_img=imgUrl
                     , sign="植物人1号"
                     )
    # 通过session进行commit提交修改
    userDb.session.add(user_data)  # 先添加
    userDb.session.commit()  # 后提交

    return Result.success("注册成功")


# 通过id获取个人信息
@user_blueprint.route('/getUserInfoById', methods=['GET'])
def getUserInfoById():
    # 获取传入的个人id
    id = request.args.get("id")
    # 通过id获取个人信息
    user = User.query.filter(User.id == id).all()
    # json转换
    jsonData = to_json_all(user)
    # 成功返回
    return Result.success(jsonData)


# 获取用户的点赞和文章统计
@user_blueprint.route('/getUserCount')
def getUserCount():
    # 查询所有点赞对应的作者id
    sql = "SELECT author_id FROM " \
          "plants WHERE plant_id " \
          "in (SELECT plantId FROM `userlike`)"
    likeRes = runSql(sql)
    likeList = json.loads(likeRes)
    user_id = int(request.args.get("id"))
    likes = 0
    # 通过传入的作者id进行统计
    for item in likeList:
        id = item["author_id"]
        # 匹配到相应的作者id，点赞数+1
        if id == user_id:
            likes = likes + 1
    # 文章统计sql 根据作者id统计
    countSql = "SELECT count(*) as `count` FROM " \
               "plants WHERE author_id = {}".format(user_id)
    sqlData = runSql(countSql)
    plantount = json.loads(sqlData)
    # 单独取出统计结果
    count = plantount[0]["count"]
    # 把点赞统计和文章统计放在一起
    res = {
        "like": likes,
        "count": count
    }
    return Result.success(res)


# 获取用户已发布的文章
@user_blueprint.route('/getPlants')
def getUserPlants():
    id = request.args.get("id")
    page_size = 5  # 每页最大条数
    page_index = int(request.args.get("page"))  # 页数
    try:
        # 通过发布时间排序的分页数据（通过文章查询当前用户id的文章）
        plants = Plants.query.filter(Plants.author_id == id).order_by(desc(Plants.posted_date)).limit(page_size).offset(
            (page_index - 1) * page_size).all()
        if not plants:  # 可能没有文章的时候
            return Result.errorMsg("没有数据")
        for plant in plants:
            # 存在文章，转换时间格式
            plant.posted_date = plant.posted_date.strftime('%Y-%m-%d %H:%M:%S')
            # 对文章太长的内容进行一个分隔
            plant.description = plant.description[:20] + "..."
        res = to_json_all(plants)
        return Result.success(res)
    except:
        return Result.error()


# 获取用户已点赞的文章
@user_blueprint.route('/getLikes')
def getUserLike():
    id = request.args.get("id")
    # 先查询用户喜欢了哪些文章
    res = runSql("SELECT plantId FROM userlike WHERE user_id = {}".format(id))
    plantIds = []
    # 是否用户没有点赞过的文章
    if len(res) == 2:
        return Result.error()
    else:
        for ids in json.loads(res):
            plantIds.append(ids["plantId"])
    # 然后进行分页查询点赞文章的数据
    page_size = 5
    page_index = int(request.args.get("page"))
    try:
        # 也是通过作者id和文章id查询相应文章
        plants = Plants.query \
            .filter(Plants.author_id == id, Plants.plant_id.in_(plantIds)) \
            .order_by(desc(Plants.posted_date)) \
            .limit(page_size).offset((page_index - 1) * page_size) \
            .all()
        if not plants:
            return Result.error()
        for plant in plants:
            # 转换日期和分隔长的字符
            plant.posted_date = plant.posted_date.strftime('%Y-%m-%d %H:%M:%S')
            plant.description = plant.description[:20] + "..."
        res = to_json_all(plants)
        return Result.success(res)
    except:
        return Result.error()


# 修改用户信息
@user_blueprint.route('/update', methods=['POST'])
def updateUser():
    # 获取 POST 请求的 JSON 数据
    data = request.get_json()
    # 获取具体字段
    username = data['username']
    sign = data['sign']
    imgUrl = data['imgUrl']
    id = data['id']
    # 先通过ID查询用户
    user = User.query.filter(User.id == id).first()
    if user:
        if len(username) != 0:
            user.nick_name = username
        if len(sign) != 0:
            user.sign = sign
        if len(imgUrl) != 0:
            user.title_img = imgUrl
    # 提交修改到数据库
    userDb.session.commit()
    return Result.success("修改成功")
